#'
#' @title Convert Character Columns to Factor in a Data Frame
#' @description This function takes a data frame and converts its character columns to factors. 
#' It also allows the user to specify additional character vectors that should be converted to factors.
#' The function saves the unique factor levels to a file for future reference.
#' @details The function first converts all factor columns to character, then replaces empty strings with NA. 
#' It then converts all character columns to factors. The function loads previously saved factor levels from a file, 
#' appends new levels if provided, and ensures all levels are unique before saving them back to the file. 
#' Finally, it updates the factor levels in the data frame to match the saved levels.
#' @param Df A data frame whose character columns need to be converted to factors.
#' @param ... Variable length arguments, each being a character vector specifying levels for factor conversion. 
#' For example, `c('G1', 'G2', 'G3')`, `c('G1/G2', 'G3/G4')`.
#' @usage forest_data <- Chr2Fct(forest_data, c('G1', 'G2', 'G3'), c('G1/G2', 'G3/G4'))
#' @export
#' @return A data frame with character columns converted to factors.
#' @author *WYK*
#'
Chr2Fct <- function(Df, ...) {
    library(tidyverse)
    require(rlist)

    Df <- Df %>%
        mutate_if(is.factor, as.character)

    dir <- "/Pub/Users/wangyk/Project_wangyk/Codelib_YK/some_scr/"

    Df[(Df == "")] <- NA

    Df <- Df %>%
        mutate_if(is.factor, as.character) %>%
        mutate_if(is.character, as_factor)

    load(file.path(dir, ".p.RData"))

    x_tmp <- list(...)
    # x_tmp <- list( c("Elevated", "Low", "Normal"), c("Elevated", "Normal"), c("G1", "G2", "G3", "G4"))

    if (length(x_tmp) > 1) {
        walk(seq_len(length(x_tmp)), function(len_x) {
            .p <<- rlist::list.append(.p, x_tmp[[len_x]])
        })
    }

    .p <- unique(.p)
    save(.p, file = file.path(dir, ".p.RData"))

    walk(colnames(Df), function(x) {
        if (is.factor(Df[[x]])) {
            lapply(.p, function(parameter) {
                if (isTRUE(all.equal(levels(Df[[x]]) %>% sort(), parameter %>% sort()))) {
                    Df[[x]] <<- factor(Df[[x]], levels = parameter)
                    return()
                }
            })
        }
    })

    return(Df)
}

# add_factory <- function() { env <- environment() env$x <- 0 add <- function(x
# = 1){ env$x <- env$x + x env$x } add }

# add <- add_factory()


